<?php


interface PartitionExpanderinterface 
{
	function build_partition_info($state);
}

class MYSQLPartitionExpander implements PartitionExpanderinterface
{

	function build_partition_info($state){

		$sql = "SELECT 
			TABLE_NAME,
		    PARTITION_NAME,
		    PARTITION_METHOD,
		    PARTITION_EXPRESSION,
		    PARTITION_DESCRIPTION
		FROM
		    information_schema.partitions
		WHERE
		    TABLE_NAME IN('" . implode(',', array_keys($state->tables)) . "')
		    AND 
		    TABLE_SCHEMA = '{$state->tmp_shard['db']}'";

		   var_dump($sql); 
 
 		if(!$stmt = $state->DAL->my_query($sql)) throw new Exception('could not access partition schema: ' . $state->DAL->my_error());

 		$data = array();
		while($row = $state->DAL->my_fetch_assoc($stmt)) {
			$table_name = $row['TABLE_NAME'];
			$column = $row['PARTITION_EXPRESSION'];

			if($row['PARTITION_METHOD'] == 'RANGE COLUMNS'){
				$data[$table_name]['partition_type'] = 'RANGE';
				$data[$table_name][$column][] = $row['PARTITION_DESCRIPTION'];
			}

			if($row['PARTITION_METHOD'] == 'RANGE LIST'){
				$data[$table_name]['partition_type'] = 'LIST';
				$data[$table_name][$column][] = explode(',', $row['PARTITION_DESCRIPTION']);
			}
		}

		return $data;
	}

}



class PGSQLPartitionExpander implements PartitionExpanderinterface
{
	function build_partition_info($state){
		//TODO
	}
}

class PartitionExpander
{
	public static function factory($rdbms_type){

		//mysql
		if(preg_match('/mysql/', $rdbms_type)){
			return new MYSQLPartitionExpander();
		}

		//pgsql
		if(preg_match('/pgsql/', $rdbms_type)){
			return new PGSQLPartitionExpander();
		}

		throw new Exception('Unsupported RDBMS: ' . $rdbms_type);
	}
}

?>